<?php

namespace app\admin\controller;

use app\admin\common\Constants;
use app\admin\model\Config;
use think\Db;
use think\Exception;

class Approval extends \app\admin\controller\Backend
{
    protected $model = null;
    private $searchFields = ['name', 'status'];

    private $userModel = null;

    private $staffModel = null;

    private $configModel = null;

    private $approverModel = null;

    private $sealModel = null;
    protected $needSelectCompany = true;
    protected $beforeActionList = [
        'getCurrentCompany',
        'permitNew' => ['only' => 'save'],
    ];

    public function _initialize()
    {
        $this->model = new \app\admin\model\Approval();
        $this->sealModel = new \app\admin\model\Seal();
        parent::_initialize();
        $this->configModel = new Config();
        $this->staffModel = new \app\admin\model\Staff();
        $this->userModel = new \app\admin\model\User();
        $this->approverModel = new \app\admin\model\Approver();
    }

    public function add($sealId = null)
    {
        $seal = $this->sealModel->where('company_id', $this->company->id)->find($sealId);
        if (!$seal) {
            $this->error("印章不存在，无法更新");
        }

        $this->existModel();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['company_id'] = $this->company->id;
            $data['seal_id'] = $sealId;
            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
            if ($result !== false) {
                $this->success("成功", url('settingApproval', ['sealId' => $sealId]));
            } else {
                $this->error($this->model->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 审核类型列表配置
     * @param $sealId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function settingApproval($sealId)
    {
        $seal = $this->sealModel->where('company_id', $this->company->id)->find($sealId);
        if (!$seal) {
            $this->error("印章不存在");
        }
        if ($this->request->ext() == 'json') {
            $paginate = $this->model->where("seal_id", $sealId)->paginate();
            $this->success('ok', null, $paginate);
        }
        $staffs = $this->staffModel->where('company_id', $this->company->id)->select();
        $this->assign('users', []);
        $uid = array_map(function ($item) {
            return $item->uid;
        }, $staffs);
        if (sizeof($uid)) {
            $value = $this->userModel->where('id', 'in', $uid)->select();
            $this->assign('users', $value);
        }
        $paginate = $this->model->where("seal_id", $sealId)->paginate();
        $this->assign('list', $paginate);
        $this->assign("seal", $seal);

        return $this->fetch();
    }

    public function edit($sealId = null)
    {
        $seal = $this->sealModel->where('company_id', $this->company->id)->find($sealId);
        if (!$seal) {
            $this->error("印章不存在");
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $row = $this->model->where('id', $params['id'])->find();
            if (!$row) {
                $this->error('记录不存在');
            }
            /**
             * 重新生成token
             */
            $this->request->token();
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->update($params);
                    Db::commit();
                    if ($this->request->isAjax()) {
                        $this->success("更新成功", url("settingApproval", ['sealId' => $seal->id]));
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("成功");
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
        $department = \app\admin\model\Department::where(["company_id" => $this->company->id])->select();
        $this->assign('companyIds', explode(",", $row->department));
        $this->assign('departments', $department);
        $sealTypes = $this->configModel->getSealTypes();
        $sealStatus = $this->configModel->getSealStatus();
        $this->assign('sealTypes', $sealTypes);
        $this->assign('sealStatuses', $sealStatus);
        $this->assign('__token__', $this->request->token());
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 更新审批流程
     * @param $id
     */
    public function updateSetting($id)
    {
        $entity = $this->model->with(['seal', 'approvers'])->find($id);
        if ($this->request->isPost()) {
            $this->checkToken();
            $this->request->token();
            $params = $this->request->post();
            if (!$entity) {
                $this->error('审批类型不存在');
            }
            $approvers = $params['approvers'];
            Db::startTrans();
            try {
                //是否采用模型验证
                foreach ($entity->approvers as $approver) {
                    if (!in_array($approver->uid, $approvers)) {
                        $approver->delete();
                    } else {
                        $position = array_search($approver->uid, $approvers) + 1;
                        $this->approverModel->where('id', $approver->id)->update(['sort' => $position]);
                    }
                }
                $oldUid = array_map(function ($item) {
                    return $item->uid;
                }, $entity->approvers);
                $diff = array_diff($approvers, $oldUid);

                $rows = [];
                $createTime = time();
                foreach ($diff as $uid) {
                    $rows[] = [
                        'app_id'      => $entity->id,
                        'uid'         => $uid,
                        'sort'        => array_search($uid, $approvers) + 1,
                        'create_time' => $createTime,
                    ];
                }
                $this->approverModel->saveAll($rows);
                Db::commit();
                $this->success("更新成功", url("index"));
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->error('未更新');
        }
        $this->error('Method is not supported get ');
    }

    public function index()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        if ($this->request->param('name')) {
            $where ['name'] = ['like', '%' . $this->request->param('name') . '%'];
        }
        if ($this->request->param('number')) {
            $where ['number'] = ['eq', $this->request->param('number')];
        }
        if ($this->request->param('seal_type')) {
            $where ['seal_type'] = ['eq', $this->request->param('seal_type')];
        }
        $where['company_id'] = $this->company->id;
		$where['is_del']=array('eq',0);
        $list = $this->sealModel->with(['creatorUser', 'updaterUser', 'cover'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $configModel = new Config();
        $this->assign('sealTypes', $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY));
        $this->assign('sealStatuses', $configModel->getConfigCacheByName(Constants::$SEAL_STATUS_KEY));
        $this->assign('list', $list);
        $value = $this->request->param();
        $this->assign('params', $value);
        return $this->fetch('index');
    }

    public function show($id = null)
    {
        $entity = $this->model->with(['seal', 'approvers.user'])->find($id);
        $this->request->token();
//        $approverList = $this->approverModel->with(['user'])->where(['app_id' => $id])->select();
        if ($this->request->ext() == 'json') {

            if ($entity->seal->company_id != $this->company->id) {
                $this->error('您无权查看该印章的审核类型');
            }
            $this->success('OK', null, $entity);
        }
    }


}